import BaseModel from './BaseModel'

export enum LoadType {
  loading,  // 加载中
  loaded,   // 加载完成
  finish    // 加载全部
}

class YBListLoad<T> {

  // 数据数组
  public dataArr = []

  // 当前分析
  private page = 1
  // 其他数据（会传送的加载的对象）
  public otherData: T
  // 加载状态
  private loadType: LoadType = LoadType.loaded
  // 模型类
  private modelType: any
  // 请求链接
  private url: string

  // 构造方法
  constructor(modelType: any, url: string, otherData: T) {
    this.otherData = otherData
    this.modelType = modelType
    this.url = url
  }

  // 加载数据 loadName: 加载的列表名称
  public loadData(loadName = 'loadModels') {
    return new Promise((resolve, reject) => {
      if (this.loadType === LoadType.loaded) {
        this.loadType = LoadType.loading
        this.modelType[loadName](this.url, this.page, this.otherData).then((dataArr: any) => {
          this.page += 1
          this.dataArr = this.dataArr.concat(dataArr)
          this.loadType = dataArr.length < 20 ? LoadType.finish : LoadType.loaded
          resolve(this.dataArr)
        }).catch((err: any) => {
          this.loadType = LoadType.loaded
          const p = {
            load: true,
            err,
          }
          reject(p)
        })
      } else {
        const p = { load: true }
        reject(p)
      }
    })
  }

  // 清除数据
  public clearData() {
    this.page = 1
    this.dataArr = []
    this.loadType = LoadType.loaded
  }
}

export default YBListLoad
